package com.zhyaoqi.platformautoplug.util;

import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.GestureDescription;
import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.graphics.Path;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.Toast;

import androidx.annotation.RequiresApi;

import com.zhyaoqi.platformautoplug.service.PlugService;

import java.util.List;
import java.util.Random;

import static android.content.Context.CLIPBOARD_SERVICE;

/**
 * description ：无障碍工具类
 * author : ZF
 * date : 2020/8/12 10：10
 */
public class AccessibilityUtil {
    private AccessibilityNodeInfo rootNodeInfo;
    private Context mContext;

    public void initAccessibilityUtil(AccessibilityNodeInfo nodeInfo, Context context) {
        this.rootNodeInfo = nodeInfo;
        this.mContext = context;
        Log.e("ZF", "-------AccessibilityUtil初始化成功--------");
    }

    /**
     * 根据View的ID搜索符合条件的节点,精确搜索方式;
     * 这个只适用于自己写的界面，因为ID可能重复
     * api要求18及以上
     * AccessibilityNodeInfo ：查找view的节点
     * viewId : view的id
     *
     * @param viewId
     */
    public List<AccessibilityNodeInfo> findNodesById(AccessibilityNodeInfo rootNodeInfo, String viewId) {
        if (rootNodeInfo != null) {
            if (Build.VERSION.SDK_INT >= 18) {
                return rootNodeInfo.findAccessibilityNodeInfosByViewId(viewId);
            } else {
                Toast.makeText(mContext, "版本号太低无法使用此功能", Toast.LENGTH_LONG).show();
            }
        }
        return null;
    }

    /**
     * 根据找到view的id延时不固定时间并进行点击
     * 12~20秒取随机数进行延时
     */
    public void findByIdClick(String viewId) {
        List<AccessibilityNodeInfo> infoList = findNodesById(rootNodeInfo, viewId);

        for (AccessibilityNodeInfo item : infoList) {
            long t = randomNumber(12, 20);
            try {
                Thread.sleep(t);

            } catch (Exception ex) {
                ex.printStackTrace();
            }

            clickView(item);
        }
    }

    /**
     * 点击该控件
     *
     * @return true表示点击成功
     */
    public static boolean clickView(AccessibilityNodeInfo nodeInfo) {
        if (nodeInfo != null) {
            if (nodeInfo.isClickable()) {
                nodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                return true;
            } else {
                AccessibilityNodeInfo parent = nodeInfo.getParent();
                if (parent != null) {
                    boolean b = clickView(parent);
                    //释放资源
                    parent.recycle();
                    if (b) return true;
                }
            }
        }
        return false;
    }

    /**
     * 长按控件
     * 暂未测试
     *
     * @return true表示点击成功
     */
    public static boolean clickLongView(AccessibilityNodeInfo nodeInfo) {
        if (nodeInfo != null) {
            if (nodeInfo.isClickable()) {
                nodeInfo.performAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
                return true;
            } else {
                AccessibilityNodeInfo parent = nodeInfo.getParent();
                if (parent != null) {
                    boolean b = clickView(parent);
                    parent.recycle();
                    if (b) return true;
                }
            }
        }
        return false;
    }


    /**
     * 找到viewId
     * 12~20秒取随机数
     * 进行滑动
     * <p>
     * AccessibilityNodeInfo.ACTION_SCROLL_FORWARD:屏幕侧滑
     * findByIdScroll("com.ss.android.ugc.aweme:id/erj");
     */
    public void findByIdScroll(String viewId) {
        List<AccessibilityNodeInfo> mTvTuiJian = findNodesById(rootNodeInfo, viewId);

        for (AccessibilityNodeInfo item : mTvTuiJian) {
            long t = 12000 + new Random().nextInt(5800);
            try {
                Thread.sleep(t);

            } catch (Exception ex) {
                ex.printStackTrace();
            }
            item.performAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
        }
    }


    /**
     * 根据概率随机进行点击
     * 适用于根据一个概率进行点赞或者评论
     *
     * @param proportion 百分比的值
     * @param viewId     操作点击事件view的id
     */
    public void mRandomFindViewById(int proportion, String viewId) {
        double floor = Math.floor(Math.random() * (100 - 1 + 1)) + 1;
        if (floor <= proportion) {
            List<AccessibilityNodeInfo> mTvTuiJian = findNodesById(rootNodeInfo, viewId);
            for (AccessibilityNodeInfo item : mTvTuiJian) {
                clickView(item);
            }
        }
    }


    /**
     * 在一个时间段内产生一个随机数
     *
     * @param minTime :最短时长（必须大于0）
     * @param maxTime :最长时长（必须大于0）
     */
    public long randomNumber(int minTime, int maxTime) {
        if (minTime != 0 && maxTime != 0) {
            return (long) (Math.floor(Math.random() * (maxTime - minTime + 1)) + minTime) * 1000;
        }
        return 0;
    }

    /**
     * 评论
     * 1、找到评论图标，进行点击，弹出评论列表弹窗
     * 2、弹窗中寻找评论editText，粘贴评论内容
     * 3、找到发送评论按钮进行发送
     * 4、关闭弹窗
     *
     * @param content :评论内容
     */
    public void mComment(AccessibilityService service, String content) {
        try {
            //评论imageView
            List<AccessibilityNodeInfo> mImComment = rootNodeInfo.findAccessibilityNodeInfosByViewId("com.ss.android.ugc.aweme:id/aeo");
            for (AccessibilityNodeInfo item : mImComment) {
                clickView(item);
                Thread.sleep(1580);

                //评论的EditText
                List<AccessibilityNodeInfo> infos_pl2 = rootNodeInfo.findAccessibilityNodeInfosByViewId("com.ss.android.ugc.aweme:id/adq");
                for (AccessibilityNodeInfo item1 : infos_pl2) {
                    LogUtils.logGGQ("item1:" + item1.getViewIdResourceName());
                    //粘贴板
                    ClipboardManager clipboard = (ClipboardManager) service.getSystemService(CLIPBOARD_SERVICE);
                    ClipData clip = ClipData.newPlainText("label", content);
                    clipboard.setPrimaryClip(clip);

                    Bundle bundle = new Bundle();
                    bundle.putCharSequence(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, content);
                    Thread.sleep(5380);
                    item1.performAction(AccessibilityNodeInfo.ACTION_SET_TEXT, bundle);
                    Thread.sleep(5380);

                    //评论完成后的发送按钮
                    List<AccessibilityNodeInfo> infos_fs3 = rootNodeInfo.findAccessibilityNodeInfosByViewId("com.ss.android.ugc.aweme:id/ae9");
                    for (AccessibilityNodeInfo item3 : infos_fs3) {

                        clickView(item3);
                        Thread.sleep(5380);

                        //关闭评论弹窗
                        List<AccessibilityNodeInfo> infos_guanbi = rootNodeInfo.findAccessibilityNodeInfosByViewId("com.ss.android.ugc.aweme:id/ks");

                        for (AccessibilityNodeInfo item4 : infos_guanbi) {
                            clickView(item4);
                            Thread.sleep(1380);
                        }
                    }
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 评论
     * 给粘贴板赋值
     * 未测试
     */
    @SuppressLint("ObsoleteSdkInt")
    public static boolean InputText(AccessibilityService service, AccessibilityNodeInfo nodeInfo, String text) {
        if (service == null) return false;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Bundle arguments = new Bundle();
            arguments.putCharSequence(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, text);
            return nodeInfo.performAction(AccessibilityNodeInfo.ACTION_SET_TEXT, arguments);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            ClipboardManager clipboard = (ClipboardManager) service.getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData clip = ClipData.newPlainText("label", text);
            if (clipboard != null) {
                clipboard.setPrimaryClip(clip);
            }
            nodeInfo.performAction(AccessibilityNodeInfo.ACTION_FOCUS);
            nodeInfo.performAction(AccessibilityNodeInfo.ACTION_PASTE);
        }
        return false;
    }

    /**
     * 先上滑动手势
     */
    public void mUpSlip(AccessibilityService service) {
        //仿滑动
        try {
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
                Path path = new Path();
                path.moveTo(540, 2000);//滑动起点
                Thread.sleep(2500);
                path.lineTo(540, 100);//滑动终点
                Thread.sleep(8000);
                GestureDescription.Builder builder = new GestureDescription.Builder();
                GestureDescription description = builder.addStroke(new GestureDescription.StrokeDescription(path, 100L, 100L)).build();
                //100L 第一个是开始的时间，第二个是持续时间
                service.dispatchGesture(description, new MyCallBack(), null);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    @RequiresApi(api = Build.VERSION_CODES.N)
    private class MyCallBack extends AccessibilityService.GestureResultCallback {

        public MyCallBack() {
            super();
        }

        @Override
        public void onCompleted(GestureDescription gestureDescription) {
            super.onCompleted(gestureDescription);

        }

        @Override
        public void onCancelled(GestureDescription gestureDescription) {
            super.onCancelled(gestureDescription);

        }
    }

}
